package com.joshua.spring.controller;

import com.joshua.spring.constant.ProviderApiConstants;
import com.joshua.spring.entity.Consumer;
import com.joshua.spring.entity.vo.GlobalResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import static com.joshua.spring.constant.ConsumerApiConstants.Rest.*;

/**
 * projectName dragon-cloud
 * package com.joshua.spring.controller
 * classname  RestTemplateController
 * <p>
 * description
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/9/5 16:57
 */
@Slf4j
@RestController(BASE_PATH)
public class RestTemplateController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping(LB0)
    public GlobalResponse testLb0() {
        ServiceInstance serviceInstance = loadBalancerClient.choose(ProviderApiConstants.APPLICATION_CODE);
        String url = String.format("http://%s:%s%s", serviceInstance.getHost(), serviceInstance.getPort()) + "/msg";
        RestTemplate restTemplate = new RestTemplate();
        GlobalResponse<Consumer> response = restTemplate.getForObject(url, GlobalResponse.class);
        log.info("response:{}", response);
        return response;
    }


    @GetMapping(LB1)
    public GlobalResponse testLb1() {
        GlobalResponse<Consumer> response = localRestTemplate().getForObject(
                String.format("http://%s%s",ProviderApiConstants.APPLICATION_CODE,""), GlobalResponse.class);
        log.info("response:{}", response);
        return response;
    }

    @LoadBalanced
    private RestTemplate localRestTemplate() {
        return new RestTemplate();
    }

}
